package com.qiantu.phone.other;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

import com.qiantu.phone.utils.StringUtil;

public class LimitCharLengthTextWatcher implements TextWatcher {

    private int beforeChar;
    private int charMaxLength;
    private boolean isOver;
    private int start;
    private int before;
    private int count;
    private EditText mEditText;

    public LimitCharLengthTextWatcher(EditText editText, int charMaxLength){
        this.charMaxLength = charMaxLength;
        mEditText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//        if(!isOver){
//            String text = s.toString();
//            this.beforeChar = StringUtil.getCharacterByLimit(text, charMaxLength);
//        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(!isOver){
            Log.i("lzxlzx", "s:" + s + ",start:" + start + ",before:" + before + ",count:" + count);
            this.start = start;
            this.before = before;
            this.count = count;
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
//        if(!isOver){
//            String text = s.toString();
//            if (StringUtil.getCharacterLength(text) > charMaxLength) {
//                isOver = true;
//                s.replace(0, s.length(), beforeChar);
//                isOver = false;
//            }
//        }
        if(!isOver) {
            String text = s.toString();
            String newText = StringUtil.getCharacterByLimit(text, charMaxLength);
            if (text.equals(newText)) {
                isOver = false;
            } else {
                isOver = true;
                s.replace(0, s.length(), newText);
                if(start + count <= mEditText.length()){
                    mEditText.setSelection(start + count);
                }
                isOver = false;
            }
        }
    }
}
